/**
 * 3η ΓΕ 2013-2014 - Super Market
 * ΦΡΑΓΚΟΥΛΟΠΟΥΛΟΥ ΕΜΜΑΝΟΥΕΛΑ (69298)
 * ΧΑΛΔΑΣ ΧΑΡΑΛΑΜΠΟΣ (69305)
 * ΧΟΡΜΟΒΙΤΗΣ ΙΩΑΝΝΗΣ (69325)
 * ΧΟΥΣΤΟΥΛΑΚΗ ΕΥΑΓΓΕΛΙΑ (69327)
 */
package administratorGUI;

import java.awt.Component;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.*;
import static javax.swing.JOptionPane.INFORMATION_MESSAGE;
import static javax.swing.JOptionPane.YES_NO_OPTION;
import static javax.swing.JOptionPane.YES_OPTION;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import model.*;
import org.jdesktop.beansbinding.Binding;
import supermarket.EntityManagerFactory;

/**
 * Πίνακας Προϊόντων
 */
public class ProductsForm extends javax.swing.JInternalFrame {

    /**
     * Constructor
     */
    public ProductsForm() {
        initComponents();
        rebindProductsTable();
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        SuperMarketPUEntityManager = java.beans.Beans.isDesignTime() ? null : EntityManagerFactory.getEntityManager();
        productQuery = java.beans.Beans.isDesignTime() ? null : SuperMarketPUEntityManager.createQuery("SELECT p FROM Product p");
        productList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : productQuery.getResultList();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        productsTable = new javax.swing.JTable();
        newProductButton = new javax.swing.JButton();
        editProductButton = new javax.swing.JButton();
        deleteProductButton = new javax.swing.JButton();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Διαχείριση Προϊόντων");
        setToolTipText("");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, productList, productsTable, "PRODUCT_BIND");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${code}"));
        columnBinding.setColumnName("Κωδικός");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${points}"));
        columnBinding.setColumnName("Πόντοι");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${price}"));
        columnBinding.setColumnName("Τιμή");
        columnBinding.setColumnClass(Float.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(productsTable);

        newProductButton.setText("Νέο προϊόν");
        newProductButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newProductButtonActionPerformed(evt);
            }
        });

        editProductButton.setText("Επεξεργασία");
        editProductButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editProductButtonActionPerformed(evt);
            }
        });

        deleteProductButton.setText("Διαγραφή");
        deleteProductButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteProductButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 496, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, deleteProductButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 126, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, editProductButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 126, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, newProductButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 126, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(newProductButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(editProductButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(deleteProductButton)))
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(0, 0, 0))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void rebindProductsTable() {
        Binding b = bindingGroup.getBinding("PRODUCT_BIND");
        b.unbind();
        b.bind();
        
        TableCellRenderer dtcr = new DefaultTableCellRenderer() {
            NumberFormat nf = new DecimalFormat("#,##0.00");

            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus,
                    int row, int column) {
                if (value instanceof Float) {
                    value = nf.format(value);
                    setHorizontalAlignment(SwingConstants.RIGHT);
                } else if (value instanceof Integer) {
                    setHorizontalAlignment(SwingConstants.RIGHT);
                } else {
                    setHorizontalAlignment(SwingConstants.LEFT);
                }
                return super.getTableCellRendererComponent(table, value, isSelected,
                        hasFocus, row, column);
            }
        };

        for (int i = 0; i < productsTable.getModel().getColumnCount(); ++i) {
            productsTable.getColumnModel().getColumn(i).setCellRenderer(dtcr);
        }

    }

    /**
     * Button: Διαγραφή
     *
     * @param evt
     */
    private void deleteProductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteProductButtonActionPerformed
        // Ελέγχω αν υπάρχει επιλεγμένο Row στο Table
        int row = productsTable.getSelectedRow();
        if (row < 0) {
            JOptionPane.showMessageDialog(this, "Δεν έχετε επιλέξει εγγραφή.",
                    "Προσοχή!", INFORMATION_MESSAGE);
            return;
        }
        Product product = productList.get(row);
        EntityManagerFactory.getEntityManager().refresh(product);
        
        // Warning αν το Προϊόν ανήκει σε Κατάστημα         
        if (!product.getStoreList().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Έχετε συσχετίσει το "
                    + "προϊόν με " + product.getStoreList().size()
                    + " Καταστήματα.\nΑν επιλέξετε 'Διαγραφή', θα διαγράψετε "
                    + "και τους συσχετισμούς.", "Προσοχή", INFORMATION_MESSAGE);
        }

        // Warning αν το Προϊόν έχει χρησιμοποιηθεί από Αγορές
        if (!product.getProductPurchaseList().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Έχετε πραγματοποιήσει "
                    + product.getProductPurchaseList().size() + " Αγορές με "
                    + "το συγκεκριμένοπροϊόν.\nΑν επιλέξετε 'Διαγραφή', "
                    + "θα διαγράψετε και τις Αγορές.", "Προσοχή", 
                    INFORMATION_MESSAGE);
        }

        // Ερώτηση
        if (JOptionPane.showConfirmDialog(this,
                "Να διαγραφεί η επιλεγμένη εγγραφη;",
                "Διαγραφή", YES_NO_OPTION) == YES_OPTION) {

            SuperMarketPUEntityManager.getTransaction().begin();
            SuperMarketPUEntityManager.remove(product);
            SuperMarketPUEntityManager.getTransaction().commit();
            productList.clear();
            productList.addAll(productQuery.getResultList());
            rebindProductsTable();
            productsTable.updateUI();
        }
    }//GEN-LAST:event_deleteProductButtonActionPerformed

    /**
     * Button: Νέο Προϊόν
     *
     * @param evt
     */
    private void newProductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProductButtonActionPerformed
        // TODO add your handling code here:
        NewProductDialog np = new NewProductDialog(null, true);
        np.setLocationRelativeTo(this);

        np.setVisible(true);
        if (np.isValidForSave()) {
            saveRecord(np);
        }
    }//GEN-LAST:event_newProductButtonActionPerformed

    private void editProductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editProductButtonActionPerformed
        // TODO add your handling code here:
        int row = productsTable.getSelectedRow();
        if (row < 0) {
            JOptionPane.showMessageDialog(this, "Δεν έχετε επιλέξει εγγραφή.",
                    "Προσοχή!", INFORMATION_MESSAGE);
            return;
        }

        Product currentProduct = productList.get(row);
        NewProductDialog np = new NewProductDialog(null, true);
        np.setLocationRelativeTo(this);
        np.setProduct(currentProduct);
        np.setVisible(true);

        if (np.isValidForSave()) {
            saveRecord(np, currentProduct);
        }
    }//GEN-LAST:event_editProductButtonActionPerformed

    /**
     * Save Record
     */
    private void saveRecord(NewProductDialog np, Product product) {

        product.setName(np.getProductName());
        product.setCode(np.getProductCode());
        product.setPoints(np.getProductPoints());
        product.setPrice(np.getProductPrice());

        SuperMarketPUEntityManager.getTransaction().begin();
        SuperMarketPUEntityManager.persist(product);
        SuperMarketPUEntityManager.getTransaction().commit();
        productList.clear();
        productList.addAll(productQuery.getResultList());
        rebindProductsTable();
        productsTable.updateUI();
    }

    /**
     * Save Record (mode: New Record)
     */
    private void saveRecord(NewProductDialog np) {
        saveRecord(np, new Product());
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager SuperMarketPUEntityManager;
    private javax.swing.JButton deleteProductButton;
    private javax.swing.JButton editProductButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton newProductButton;
    private java.util.List<model.Product> productList;
    private javax.persistence.Query productQuery;
    private javax.swing.JTable productsTable;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
